import { Component, Input, OnInit, AfterViewInit } from '@angular/core';
import { TreeNode } from 'primeng/primeng';
import { QkPartService } from './qkpart.service';
@Component({
  selector: 'qkhuman-selector',
  templateUrl: './qkhuman-selector.component.html',
  styleUrls: ['./qkhuman-selector.component.scss'],
  providers: [QkPartService]
})
export class QkHumanSelectorComponent implements OnInit {
  @Input() checkedParts: TreeNode[];
  checkedHumans: TreeNode[] = [];
  loading: boolean = true;
  parts: any[];
  unitHumans: TreeNode[] = []; //人员机构树
  suggestions: any[];
  suggestion: any;

  constructor(private qkPartService: QkPartService) { }

  ngOnInit() {
    this.qkPartService.getUnitHumanTree(0, true)
      .subscribe(data => {
        this.loading = false;
        this.unitHumans = data;
        // 异步请求问题：暂时不做反选
        // this.checkedParts.forEach(node => {
        //   if (node['data']['type'] == '人员') {
        //     this.recursionExpendSuggestionTreeNode(this.unitHumans, node['data']['unitCode'], node['id']);
        //   }
        // });
      });
  }

  /** 人员查找 */
  search(event) {
    if (!event.query) return;
    this.qkPartService.searchUnitHumanByName(event.query).subscribe(data => this.suggestions = data);
  }

  /**选择下拉事件 */
  selectSuggestion() {
    this.recursionExpendSuggestionTreeNode(this.unitHumans, this.suggestion.unitCode, this.suggestion.humanId);
  }

  /**树节点展开 */
  unitNodeExpand(event) {
    if (event.node && event.node.children.length == 0) {
      let unitId = +event.node.id;
      this.qkPartService.getUnitHumanTree(unitId, false).subscribe(nodes => event.node.children = nodes);
    }
  }

  /**递归展开查询的树 */
  recursionExpendSuggestionTreeNode(unitHumans: TreeNode[], unitCode: string, humanId: number) {
    unitHumans.forEach(ele => {
      let id = ele['id'];
      if ('patrol' == ele.icon && humanId == id) {
        this.checkedHumans.push(ele);
        return
      }
      if (unitCode.indexOf('/' + id + '/') != -1) {
        //展开树节点
        ele.expanded = true;
        if (ele.children && ele.children.length > 0) {
          this.recursionExpendSuggestionTreeNode(ele.children, unitCode, humanId);
        } else {
          this.qkPartService.getUnitHumanTree(id, false).subscribe(nodes => {
            ele.children = nodes;
            this.recursionExpendSuggestionTreeNode(ele.children, unitCode, humanId);
          });
        }
      }
    });
  }

}
